package com.ly.statertest.biz;

import com.fasterxml.jackson.core.JsonParseException;
import com.ly.websocket.biz.DefaultMsgSender;
import com.ly.websocket.web.WebSocketDo;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.websocket.Session;

@Component
public class MyMsgSender extends DefaultMsgSender {

    @Override
    public void send(WebSocketDo.Msg msg) throws Exception {
        System.out.println("--------------------------");
        // img:xxxx
        String content = msg.getContent();
        MsgBody msgBody;
        try{
            msgBody = objectMapper.readValue(content, MsgBody.class);
        } catch (JsonParseException e){
            // 上线,下线 不是 json
            super.send(msg);
            return;
        }

        // 重新设置内容
        msg.setContent(msgBody.getContent());
        if(msgBody.getRecvId()!=null){
            Session session = WebSocketDo.getOnlines().get(msgBody.getRecvId());
            // 再转回json
            String json = objectMapper.writeValueAsString(msg);
            // 单独发送消息->私发
            session.getBasicRemote().sendText(json);
        } else {
            super.send(msg);
        }
    }

}
